<!--
 * @FileDescription: 登录模块
 * @Author: 汤子豪
 * @Date: 2021.6.24
 * @LastEditors: 汤子豪
 * @LastEditTime: 2021.6.25
 -->
<template>
  <div>
    <el-col :span="14">
      <img src="../../assets/img/school.jpg" alt="" id="left_img" />
    </el-col>
    <el-col :span="10" id="right_login">
      <h1>教育教学改革研究系统</h1>
      <el-tabs
        v-model="loginForm.role"
        class="loginForm"
        @tab-click="handleClick"
        stretch
      >
        <el-tab-pane label="教师登录" name="1"></el-tab-pane>
        <el-tab-pane label="管理员登录" name="3"></el-tab-pane>
        <el-tab-pane label="专家登录" name="2"></el-tab-pane>
      </el-tabs>
      <el-form
        :model="loginForm"
        role-icon
        :rules="rules"
        ref="loginForm"
        class="login_Form"
      >
        <el-form-item prop="gh">
          <el-input
            v-model="loginForm.gh"
            autocomplete="off"
            placeholder="请输入工号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :type="passType"
            v-model="loginForm.password"
            autocomplete="off"
            placeholder="请输入密码"
            ><i slot="suffix" class="el-icon-view" v-bind:class="{open:isActive}" @click="showPwd"></i>
          </el-input>
        </el-form-item>
        <el-form-item prop="verifycode">
          <el-row :gutter="20">
            <el-col :span="11">
              <el-input
                v-model="loginForm.verifycode"
                autocomplete="off"
                placeholder="请输入验证码"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <div @click="refreshCode">
                <identify :identifyCode="identifyCode"></identify>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item id="select">
          <el-checkbox v-model="remember">记住密码</el-checkbox>
          <router-link to="./forget">忘记密码</router-link>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="submitForm('loginForm')"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-col>
  </div>
</template>

<script>
import Identify from "../../components/Identify.vue";
export default {
  name: "Login",
  data() {
    //工号验证
    var checkGh = (rule, value, callback) => {
      if (!value) {
        callback(new Error("工号不能为空"));
      } else {
        callback();
      }
    };
    //密码验证
    var validatepassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    //验证码验证
    var validateVerifycode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else if (value !== this.identifyCode) {
        console.log("validateVerifycode:", value);
        callback(new Error("验证码不正确!"));
      } else {
        callback();
      }
    };
    return {
      teacherInfo:this.$store.state.info,
      loginForm: {
        gh: "",
        password: "",
        verifycode: "",
        role: "1",
      },
      identifyCodes: "1234567890",
      identifyCode: "",
      remember: false,
      rules: {
        gh: [{ validator: checkGh, trigger: "blur" }],
        password: [{ validator: validatepassword, trigger: "blur" }],
        verifycode: [{ validator: validateVerifycode, trigger: "blur" }],
      },
      passType: "password",
      isActive:false
    };
  },
  mounted() {
    this.getIsRemember();
  	this.refreshCode();
  },
  methods: {
    //显示与隐藏密码
    showPwd() {
      if (this.passType == "") {
        this.passType = "password";
        this.isActive = false
      }
      else{
         this.passType = "";
         this.isActive = true;
      }
    },
    //获得记住密码状态
    getIsRemember() {
      let gh = this.$cookies.get("gh");
      let password = this.$cookies.get("password");
      if (gh != null) {
        this.remember = true;
        this.loginForm.gh = gh;
        this.loginForm.password = password;
      }
    },

    //Tabs标签点击事件监听 切换用户角色
    handleClick(tab, event) {
      this.role = tab.$options.propsData.name;
    },

    //上传登录表单
    submitForm(formName) {
      let _that = this;
      //  console.log(this.$refs[formName])
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = _that.$loading({
            lock: true,
            text: "Loading",
          });
          this.loginAxios(_that, loading);
        } else {
          console.log("错误提交");
          return false;
        }
      });
      this.refreshCode();
    },

    //登录
    loginAxios(_that, loading) {
      _that.$api.login
        .signIn({
          gh: this.loginForm.gh,
          password: this.loginForm.password,
          type: this.loginForm.role,
        })
        .then(function (response) {
          console.log(response);
          let code = response.data.code;
          let data = response.data.data;
          if(code == 4002){
            loading.close();
            _that.$message({
                  showClose: true,
                  message:"人事处无该教师信息",
                  type: "error",
                  center:true,
                  offset:(screen.height/2)-80
                });
            }

          if (code == 4004) {
            loading.close();
            _that.$message({
              showClose: true,
              message: "用户名或密码错误",
              type: "error",
			  center:true,
			  offset:(screen.height/2)-80
            });
          } else if (code == 200){
            _that.$message({
              showClose: true,
              message: "登录成功",
              type: "success",
              center:true,
              offset:(screen.height/2)-80
            });
            localStorage.clear();
            _that.$store.commit("setToken", data.token);
            _that.$store.commit("setTokenHead", data.tokenHead);
            _that.$store.commit("setJsession", data.jsession_id);
            _that.$store.commit("setRole", _that.loginForm.role);
            if (_that.remember) {
              _that.$cookies.config("7d");
              _that.$cookies.set("gh", _that.loginForm.gh);
              _that.$cookies.set("password", _that.loginForm.password);
            } else {
              _that.$cookies.set("gh", "");
              _that.$cookies.set("password", "");
            }
            _that.getNavAxios(_that, loading);
          } else if (code == 4005) {
            loading.close();
            _that.$message({
              showClose: true,
              message: "请先初始化",
              type: "warning",
			  center:true,
			  offset:(screen.height/2)-80
            });
            console.log(_that.loginForm.gh);
            _that.initRouter(_that);
          }else if(code == 4003 ){
			  loading.close();
        if(_that.loginForm.role == 2){
          _that.$message({
            showClose: true,
            message: "此教师不是专家！",
            type: "error",
          center:true,
          offset:(screen.height/2)-80
          });
        }

        if(_that.loginForm.role == 3){
          _that.$message({
            showClose: true,
            message: "此教师不是管理员！",
            type: "error",
          center:true,
          offset:(screen.height/2)-80
          });
        }

		  }
        })
        .catch(function (error) {
          console.log(error);
        });
    }, // 获取菜单栏
    getNavAxios(_that, loading) {
      _that.$api.nav
        .getNav({})
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            console.log(response.data.data);
            _that.$store.commit("setAsideList", response.data.data);
            _that.getTeacherInfo(_that, loading);
          } else
            _that.$message({
              showClose: true,
              message: "获取失败",
              type: "error",
			  center:true,
			  offset:(screen.height/2)-80
            });
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    getTeacherInfo(_that, loading) {
      _that.$api.teacher
        .getDefaultTeacherInfo({})
        .then(function (response) {
          console.log(response);
          loading.close();
          if (response.data.code == 200) {
            console.log(response.data.data);
            _that.$store.commit("setInfo", response.data.data);
            // _that.$router.push("./home");
            _that.$router.push({path:"./home"});
          } else
            _that.$message({
              showClose: true,
              message: "获取失败",
              type: "error",
			  center:true,
			  offset:(screen.height/2)-80
            });
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    //挂载初始化
    initRouter(_that) {
      const init = {
        path: "/initialize", //初始化
        name: "initialize",
        component: () => import("@/views/login/Initialize.vue"),
      };
      console.log(_that.loginForm.role);
      _that.$store.commit("setGh", _that.loginForm.gh);
      _that.$store.commit("setType", _that.loginForm.role);

      _that.$router.addRoute("sign", init);
      _that.$router.push({ path: "/initialize" });
    },

    // 清空登录表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //随机数生成
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },

    // 切换验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },

    // 生成四位随机验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
      console.log(this.identifyCode);
    },
  },
  components: {
    Identify,
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#left_img {
  width: 100%;
  height: 465px;
  zoom: 1;
}
#right_login {
  padding-left: 20px;
}
.login_Form {
  width: 100%;
  height: 100%;
  dataect-fit: cover;
}

h1 {
  text-align: center;
}

.loginForm {
  padding: 0 20px;
}
.btns {
  display: flex;
  justify-content: center;
}
::v-deep .el-tabs__nav-scroll {
  width: 50% !important;
  margin: 0 auto !important;
}
#select {
  position: relative;
  top: -15px;
  padding: 0 5px;
}
a {
  float: right;
}
.el-icon-view{
  margin-right: 10px;
}
.open{
  color:#409EFF;
}
</style>
